package org.example.service.serviceImpl;

import cn.hutool.core.date.DateUtil;
import org.example.dao.DemoMapper;
import org.example.service.DemoService;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class DemoServiceImpl implements DemoService {
    @Resource
    private DemoMapper mapper;

    /**
     * 新增装置
     */
    @Override
    public void addDevice() {
        List<Map<String, Object>> list = new ArrayList<>();

        List<Map<String, Object>> factorys = mapper.getFactory();
        List<Map<String, Object>> districts = mapper.getDistrict();
        List<Map<String, Object>> deviceTypes = mapper.getDeviceType();

        //每个类型每个地市每个装置每个厂家各生成n个装置
        int n = 10;
        //每个装置为11M+五位数
        AtomicInteger num = new AtomicInteger(mapper.getMaxDeviceCode());
        String prefix = "11M";
        districts.forEach(district -> {
            deviceTypes.forEach(deviceType -> {
                factorys.forEach(factory -> {
                    for (int i = 0; i < n; i++) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", prefix + String.format("%05d", num.addAndGet(1)));
                        map.put("name", deviceType.get("name") + "装置" + num.get());
                        map.put("class_name", String.valueOf(deviceType.get("id")));
                        map.put("district", String.valueOf(district.get("id")));
                        map.put("factory", String.valueOf(factory.get("id")));
                        list.add(map);
                    }
                });
            });
        });
        mapper.insertDevice(list);
    }

    /**
     * 增加装置日采集数据
     *
     * @param startDate 起始时间
     * @param endDate   结束时间
     */
    @Override
    public void addDeviceData(String startDate, String endDate) {
        List<String> list = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate, df);
        LocalDate end = LocalDate.parse(endDate, df);
        while (start.isBefore(end) || start.equals(end)) {
            list.add(start.format(df));
            start = start.plusDays(1);
        }
        mapper.insertDeviceData(list);
    }

    /**
     * 更新装置状态表
     */
    @Override
    public void addDeviceStatsData(String startDate, String endDate) {
        mapper.insertDeviceStatusData(startDate, endDate);
    }

    /**
     * 更新某月的报表数据
     */
    @Override
    public void addDeviceReportData(@Param("startDate") String startDate, @Param("endDate") String endDate) {
        mapper.insertDeviceReport(startDate, endDate);
    }
}
